package com.redbudcloud.common;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhxiaotong on 17-12-17.
 */
public class JsonDateValueProcessor implements JsonValueProcessor {
    private String format ="yyyy-MM-dd";

    public JsonDateValueProcessor(){

    }
    public JsonDateValueProcessor(String format){
        this.format=format;
    }

    public Object processArrayValue(Object value, JsonConfig config) {
        return process(value);
    }

    public Object processObjectValue(String key, Object value, JsonConfig config) {
        return process(value);
    }

    private Object process(Object value){
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.UK);
        if(value!=null&&!"".equals(value)){
            String className=value.getClass().getSimpleName();
            if("Date".equals(className)&&!"".equals(value)&&value!=null){
                //  Long v=((Date) value).getTime()/1000;
                return sdf.format(value);
            } else if("Time".equals(className)&&!"".equals(value)&&value!=null){
                return value.toString();
            }else if("Timestamp".equals(className)&&!"".equals(value)&&value!=null){
                Long v=((Timestamp) value).getTime();
                Date d=new Date(v);
                return sdf.format(value);
            }else{
                String re="([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))";
                Pattern pattern = Pattern.compile(re);
                Matcher matcher = pattern.matcher(value.toString());
                boolean b= matcher.matches();
                if(b){
                    try{
                        Date d=sdf.parse(value.toString());
                        return sdf.format(d);
                    }catch (Exception e){

                    }
                }
            }
        }
        return value == null ? "" : value.toString();
    }


    public static void main(String[] args) throws ParseException {
        SimpleDateFormat d=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date=d.parse("2014-06-18 15:12:24");
        long a=date.getTime();
        long aa=a/1000;
        System.out.println(aa);
    }
}
